package com.webserver5.controller;

import com.webserver5.annotations.Controller;
import com.webserver5.annotations.RequestMapping;
import com.webserver5.http.HttpServletRequest;
import com.webserver5.http.HttpServletResponse;
import com.webserver5.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Controller
public class ArticleController {
    @RequestMapping("/writeArticle")
    public void write(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理发表文章功能");
        String title = request.getParameters("title");
        String author = request.getParameters("author");
        String content = request.getParameters("content");
        if (title == null || title.isEmpty() ||
        author == null || author.isEmpty()
        ){
            System.out.println("文章发表失败");
            response.sendRedirect("");//文章发表失败界面
            return;
        }
        try (
                Connection connection = DBUtil.getConnection();
                ){
            String sql1 = "SELECT id FROM userinfo WHERE username=?";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            ps1.setString(1,author);
            ResultSet rs = ps1.executeQuery();
            if (rs.next()){
                int id = rs.getInt("id");
                String sql2 ="INSERT INTO article (title,author,u_id) VALUES (?,?,?)";
                PreparedStatement ps2 = connection.prepareStatement(sql2);
                ps2.setString(1,title);
                ps2.setString(2,author);
                ps2.setInt(3,id);
                int num = ps2.executeUpdate();
                if (num>0){
                    System.out.println("发表成功");
                    response.sendRedirect("/writeArticle_success.html");
                }else {
                    System.out.println("发表失败");
                    response.sendRedirect("/write_article_fail.html");
                }
                ps2.close();
            }else {
                System.out.println("此作者未注册");
                response.sendRedirect("have_not+user.html");
                return;
            }
            ps1.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
